<?php
require_once $_SESSION["app_root"]."config/app.config.php";


class EntityFieldDAO
{
	/**
	 * 
	 * @return array - a list of the fields associated to the parameter <i>uuid</i> $ID
	 * @param object $ID
	 */
	public function GetAllByEntityID($ID, $orderBy = null, $getExtFormProperties = false, $getCustomFormProperties = false, $getServerProperties = false){
		$fields = array();
		$orderByStr ="";
		if($orderBy != null){
			$orderByStr = " ORDER BY `".$orderBy."`";
		}
		$query = "	SELECT 
						* 
					FROM 
						`cms_entity_fields` 
					WHERE 
						(
							(`cms_entity_fields`.`OwnerID` = '".$_SESSION["SessionUser"]->getID()."' AND `cms_entity_fields`.`U` > 0) OR
							(`cms_entity_fields`.`GroupID` IN (	SELECT 
																	`cms_user_groups`.`GroupID` 
																FROM 
																	`cms_user_groups` 
																WHERE 
																	`cms_user_groups`.`UserID` = '".$_SESSION["SessionUser"]->getID()."') AND 
								`cms_entity_fields`.`G` > 0) OR
							(`cms_entity_fields`.`W` > 0)
						) AND
						`EntityId` = '".$ID."' AND `Status` > 0
						
						".$orderByStr;
		$db = GetDatabase();
		$rs = $db->Execute($query);
		//$db->close();
		foreach ($rs as $row) {
			$field = $this->EntityFieldDataReader($row);
			$field = EntityFieldDVO::cast($field);
			if($getExtFormProperties){
				$extProps = $this->GetExtProperties($field->getID());
				$field->setExtProperties($extProps);
			}
			if($getCustomFormProperties){
				$customClientProps = $this->GetCustomClientProperties($field->getID());
				$field->setCustomClientProperties($customClientProps);
			}
			if($getServerProperties){
				$serverProps = $this->GetServerProperties($field->getID());
				$field->setServerProperties($serverProps);
			}
			array_push($fields, $field);
		}
		return $fields;
	}
	
	public function GetByID($ID, $getExtFormProperties = false, $getCustomFormProperties = false, $getServerProperties = false){
		$fields = array();
		$query = "	SELECT 
						* 
					FROM 
						`cms_entity_fields` 
					WHERE 
						(
							(`cms_entity_fields`.`OwnerID` = '".$_SESSION["SessionUser"]->getID()."' AND `cms_entity_fields`.`U` > 0) OR
							(`cms_entity_fields`.`GroupID` IN (	SELECT 
																	`cms_user_groups`.`GroupID` 
																FROM 
																	`cms_user_groups` 
																WHERE 
																	`cms_user_groups`.`UserID` = '".$_SESSION["SessionUser"]->getID()."') AND 
								`cms_entity_fields`.`G` > 0) OR
							(`cms_entity_fields`.`W` > 0)
						) AND
						`ID` = '".$ID."' AND `Status` > 0
						";
		$db = GetDatabase();
		$rs = $db->Execute($query);
		//$db->close();
		foreach ($rs as $row) {
			$field = $this->EntityFieldDataReader($row);
			$field = EntityFieldDVO::cast($field);
			if($getExtFormProperties){
				$extProps = $this->GetExtProperties($field->getID());
				$field->setExtProperties($extProps);
			}
			if($getCustomFormProperties){
				$customClientProps = $this->GetCustomClientProperties($field->getID());
				$field->setCustomClientProperties($customClientProps);
			}
			if($getServerProperties){
				$serverProps = $this->GetServerProperties($field->getID());
				$field->setServerProperties($serverProps);
			}
			$fields = $field;
		}
		return $fields;
	}
	
	public function EntityFieldDataReader($result){
		$entityField = new EntityFieldDVO(
											$result['ID'],
											$result['EntityID'],
											$result['Name'],
											$result['GridHeader'],
											$result['Type'],
											$result['DbField'],
											$result['FormLocation'],
											$result['GridLocation'],
											$result['CreatedBy'],
											$result['CreatedDate'],
											$result['ModifiedBy'],
											$result['ModifiedDate'],
											$result['OwnerID'],
											$result['Status'],
											$result['U'],
											$result['G'],
											$result['W']
											);
		return $entityField;
	}
	
	public function GetExtProperties($ID){
		$query ="
					SELECT 
						* 
					FROM 
						`cms_entity_form_field_properties`
					WHERE
						`EntityFieldID` = '".$ID."' AND
						`IsCustom` = 0 AND `IsClient` = 1
				";
		$db = GetDatabase();
		$rs = $db->Execute($query);
		$props = array();
		foreach ($rs as $row) {
			$props[$row["Name"]] = $row["Value"];
		}
		return $props;
	}
	
	public function GetCustomClientProperties($ID){
		$query ="
					SELECT 
						* 
					FROM 
						`cms_entity_form_field_properties`
					WHERE
						`EntityFieldID` = '".$ID."' AND
						`IsCustom` = 1 AND `IsClient` = 1
				";
		$db = GetDatabase();
		$rs = $db->Execute($query);
		$props = array();
		foreach ($rs as $row) {
			$props[$row["Name"]] = $row["Value"];
		}
		return $props;
	}
	
	public function GetServerProperties($ID){
		$query ="
					SELECT 
						* 
					FROM 
						`cms_entity_form_field_properties`
					WHERE
						`EntityFieldID` = '".$ID."' AND
						`IsCustom` = 1 AND `IsClient` = 0
				";
		$db = GetDatabase();
		$rs = $db->Execute($query);
		$props = array();
		foreach ($rs as $row) {
			$props[$row["Name"]] = $row["Value"];
		}
		return $props;
	}
	
	public function Create($entityField){
		$validationResult = $this->ValidateEntityField($entityField);
		$entityField = EntityFieldDVO::cast($entityField);
		if($validationResult["IsValid"]){
			$fieldArr = array(
						"ID" => $entityField->getID(),
						"EntityID" => $entityField->getEntityID(),
						"Name" => $entityField->getName(),
						"Type" => $entityField->getFieldType(),
						"DbField" => $entityField->getDbField(),
						"GridLocation" => $entityField->getGridLocation(),
						"FormLocation" => $entityField->getFormLocation(),
						"CreatedBy" => $entityField->getCreatedBy(),
						"CreatedDate" => $entityField->getCreatedDate(),
						"ModifiedBy" => $entityField->getModifiedBy(),
						"ModifiedDate" => $entityField->getModifiedDate(),
						"OwnerID" => $entityField->getOwnerID(),
						"GroupID" => $entityField->getGroupID(),
						"Status" => $entityField->getStatus(),
						"U" => $entityField->getU(), 
						"G" => $entityField->getG(), 
						"W" => $entityField->getW()
						);
			$entityDao = new EntityDAO();
			$entity = $entityDao->GetBaseByID($entityField->getEntityID());
			$alterTableQuery = $this->GenerateCreateColumnQuery($entity->getTableName(), $entityField->getDbField(), $entityField->getFieldType());
			$insertDefaultProps ="";
			$gridHeaderProperty = array(
									"ID" => uuid(),
									"EntityFieldID" => $entityField->getID(),
									"Name" => "header",
									"Value" => $entityField->getGridHeader()
									);
			$result = false;
			$db = GetDatabase();
			$db->BeginTrans();
			$result = $db->AutoExecute("cms_entity_fields", $fieldArr, 'INSERT');
			if($result){$result = $db->Execute($alterTableQuery);}
			if($result){$result = $db->AutoExecute("cms_entity_grid_field_properties", $gridHeaderProperty, 'INSERT');}
			if($result){
				$db->CommitTrans();
				$validationResult["Message"] = "Field added with success";
			}else{
				$db->RollbackTrans();
				$validationResult["IsValid"] = false;
				$validationResult["Message"] = "Field added with success";
			}
			
			$validationResult["Message"] = "Field added with success";
			return $validationResult;
		}else{
			return $validationResult;
		}
	}
	
	public function SavePropertyValue($fieldId, $name, $value, $IsCustom, $IsClient){
		$query = "SELECT * FROM `cms_entity_form_field_properties` WHERE `EntityFieldID` = '".$fieldId."' AND `Name` = '".$name."'";
		$db = GetDatabase();
		$field = $db->GetRow($query);
		$fieldBase = $this->GetByID($fieldId);
		if(sizeof($field) > 0){
			$field["Value"] = $value;
			$insertSQL = $db->AutoExecute("cms_entity_form_field_properties",$field,'UPDATE', "EntityFieldID = '".$fieldId."' AND `Name` = '".$name."'");
		}else{
			
			$field["ID"] = uuid();
			$field["EntityFieldID"] = $fieldBase->getID();
			$field["Name"] = $name;
			$field["Value"] = $value;
			$field["IsCustom"] = $IsCustom;
			$field["IsClient"] = $IsClient;
			$insertSQL = $db->AutoExecute("cms_entity_form_field_properties",$field,'INSERT');
		}
		//vp($field);
	}
	
	public function GenerateCreateColumnQuery($table, $columnName, $fieldType){
		$columnType = "VARCHAR(255)";
		switch(strtolower($fieldType)){
			case "diskfile":
			case "textfield": $columnType = "VARCHAR(255)";
				break;
			case "htmleditor":
			case "textarea": $columnType = "TEXT";
				break;
			case "TimeField": $columnType = "VARCHAR(8)";
				break;
			case "datefield": $columnType = "VARCHAR(64)";
				break;
			
		}
		$createColumnQueryString = "ALTER TABLE `".$table."` ADD `".$columnName."` ".$columnType." ";
		return $createColumnQueryString;
	}
	
	public function ValidateEntityField($entityField){
		global $EntityFieldTypes;
		$validationResult["IsValid"] = true;
		$validationResult["Message"] = array();
		$entityField = EntityFieldDVO::cast($entityField);
		$entity = new EntityDVO();
		$entityDao = new EntityDAO();
		$entity = $entityDao->GetBaseByID($entityField->getEntityID(), true);
		foreach($entity->getFields() as $tmpField){
			$field = EntityFieldDVO::cast($tmpField);
			if($field->getName() == $entityField->getName()){
				$validationResult["IsValid"] = false;
				$validationResult["Message"][] = "<b>Name</b> already in use";
			}
			if($field->getDbField() == $entityField->getDbField()){
				$validationResult["IsValid"] = false;
				$validationResult["Message"][] = "<b>Database field</b> already in use";
			}
		}
		if(!is_numeric($entityField->getGridLocation())){
			$validationResult["IsValid"] = false;
			$validationResult["Message"][] = "<b>Grid location</b> must be integer";
		}
		if(!is_numeric($entityField->getFormLocation())){
			$validationResult["IsValid"] = false;
			$validationResult["Message"][] = "<b>Form location</b> must be integer";
		}
		if(!in_array($entityField->getFieldType(), $EntityFieldTypes)){
			$validationResult["IsValid"] = false;
			$validationResult["Message"][] = "<b>Field Type</b> is not valid or is not implemented yet";
		}
		return $validationResult;
	}
	
	public function DbFieldNameIsUnique($EntityID, $DbField){
		$query = "SELECT * FROM cms_entity_fields WHERE EntityID = '".$EntityID."'";
		$db = GetDatabase();
	}
	
	public function GetFieldGridProperties($EntityFieldID){
		$query = "SELECT * FROM `cms_entity_grid_field_properties` WHERE `EntityFieldID` = '".$EntityFieldID."'";
		$db = GetDatabase();
		$rs = $db->Execute($query);
		$fieldProps = array();
		foreach ($rs as $row) {
			//$field = $this->EntityFieldDataReader($row);
			$fieldProp['ID'] = $row['ID'];
			$fieldProp['EntityFieldID'] = $row['EntityFieldID'];
			$fieldProp['Name'] = $row['Name'];
			$fieldProp['Value'] = $row['Value'];
			$fieldProps[] = $fieldProp;
			//array_push($fields, $field);
		}
		return $fieldProps;
	}
}

































?>